package com.handyshop.mall.auth.config;

import com.handyshop.mall.auth.vo.AuthUserVo;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * jwt 增强
 *
 * @author handy
 * @date 2020/11/12 17:16
 */
public class JwtTokenEnhancer implements TokenEnhancer {

    /**
     * 保存用户id返回
     *
     * @param oAuth2AccessToken    oAuth2AccessToken
     * @param oAuth2Authentication oAuth2Authentication
     * @return OAuth2AccessToken
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {
        Object principal = oAuth2Authentication.getPrincipal();
        if (!(principal instanceof AuthUserVo)) {
            return oAuth2AccessToken;
        }
        AuthUserVo authUserVo = (AuthUserVo) principal;
        Map<String, Object> info = new HashMap<>();
        info.put("userId", authUserVo.getUserId());
        ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);
        return oAuth2AccessToken;
    }

}